package com.ztsoft.user.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Slf4j
@Component
public class EnclosureFilesUtils {

    @Value("${file.enclosureFile}")
    private String enclosureFile;

    private static String enclosureFilePath;

    @PostConstruct
    private void getDataExcelFile() {
        enclosureFilePath = enclosureFile;
    }

    public static synchronized List<String> uploadFiles(MultipartFile... fileList) {
        List<String> fileNames = new ArrayList<>();
        if (fileList != null && fileList.length > 0) {
            for (MultipartFile file : fileList) {
                if (file.isEmpty()) {
                    return Collections.emptyList();
                }
                String fileName = file.getOriginalFilename();

                String generateDate = generateDate(File.separator);
                File baseFileDir = getBaseFileDir();
                File storeFileDir = new File(baseFileDir, generateDate);
                if (!storeFileDir.exists()) {
                    storeFileDir.mkdirs();
                }

                File dest = new File(storeFileDir, UUID.randomUUID().toString().replace("-", "") + fileName);
                if (dest.exists()) {
                    dest.delete();
                }
                if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
                    dest.getParentFile().mkdir();
                }
                try {
                    //保存文件
                    FileUtils.copyInputStreamToFile(file.getInputStream(), dest);
                    fileNames.add(generateDate.replace("\\", "/") + "/" + dest.getName());
                } catch (Exception e) {
                    log.error(e.toString());
                    e.printStackTrace();
                } finally {
                    try {
                        file.getInputStream().close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
            return fileNames;
        }
        return Collections.emptyList();
    }

    private static File getBaseFileDir() {
        return new File(enclosureFilePath);
    }

    public static String generateDate(String separator) {
        Calendar calendar = Calendar.getInstance();
        Date date = new Date();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        return year + separator + month;
    }
}
